package com.anysoft.web;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;

import com.anysoft.R;
import com.anysoft.event.TimeOutEvent;
import com.anysoft.home.HomeActivity;
import com.anysoft.me.base.BaseWebViewActivity;
import com.anysoft.utils.CommonUtil;
import com.anysoft.utils.MentorLogger;
import com.anysoft.utils.StringUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import butterknife.OnClick;

/**
 * Created by wwq on 2017/4/7.
 */

public class BannerUrlActivity extends BaseWebViewActivity {

    private boolean isFromGuide = false;
    public String content, temp_loadUrl;
    private String bannerTitle = "";
    private String shareUrl = "";
    private String bannerDescription;
    private String bannerPicture;
    private boolean isShareCallBack = false;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        titlebar.setVisibility(View.VISIBLE);
        rl_title_layout_2.setVisibility(View.GONE);
        getIntentValue();
        title.setText("详情");

        if (!StringUtils.isNullOrEmpty(temp_loadUrl)) {
            if (!mentorApplication.needLogin()) {
                String userId = findUserId();
                StringBuffer buffer = new StringBuffer(userId);
                String reverseLast4UserId = buffer.reverse().substring(0, 4);
                String last4UserId = new StringBuffer(reverseLast4UserId).reverse().toString();
                loadUrl = temp_loadUrl + "cno=" + getCustomerNo(findUserId())
                        + "&n=" + last4UserId;
            } else {
                loadUrl = temp_loadUrl;
            }
        } else if (!StringUtils.isNullOrEmpty(content)) {
            loadUrl = content;
        }

        leftButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isFromGuide) {
                    startActivity(new Intent().setClass(mActivity, HomeActivity.class));
                }
                finish();
            }
        });
        if (StringUtils.isNullOrEmpty(shareUrl)) {
            shareUrl = loadUrl;
        }
        //包含这个字段则可以分享,显示分享图标
        if (loadUrl.contains("sharePermit")) {
            shareButtonTitle1.setVisibility(View.VISIBLE);
        } else {
            shareButtonTitle1.setVisibility(View.INVISIBLE);
        }
        //包含这个字段可以执行分享成功或者失败的回调,调H5 js方法
        if (loadUrl.contains("shareCallback")) {
            isShareCallBack = true;
        } else {
            isShareCallBack = false;
        }
        if (CommonUtil.isNetWorkConnected(this)) {
            setWebViewConfig(loadUrl);
        }
    }

    @Override
    protected void onResume() {
        if (isShareCallBack) {
//            SharePopup.setOnShareEventLinstener(new OnShareEventLinstenerImpl() {
//                @Override
//                public void onShareSuccess() {
//                    AnalyticsEventUtils.toShareBannerEvent(BannerUrlActivity.this);
//                    mWebView.evaluateJavascript("shareSuccess()", new ValueCallback<String>() {
//                        @Override
//                        public void onReceiveValue(String s) {
//                            MentorLogger.Loge("onShareSuccess" + s);
//                        }
//                    });
//                }
//
//                @Override
//                public void onShareFail() {
//                    mWebView.evaluateJavascript("shareFail()", new ValueCallback<String>() {
//                        @Override
//                        public void onReceiveValue(String s) {
//                            MentorLogger.Loge("onShareFail" + s);
//                        }
//                    });
//                }
//
//                @Override
//                public void onShareCancel() {
//
//                }
//            });
        }
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }


    private void getIntentValue() {
        Intent intent = getIntent();
        if (!intent.getBooleanExtra("startBanner", false)) {
            shareButtonTitle1.setVisibility(View.VISIBLE);
        }
        isFromGuide = intent.getBooleanExtra("isFromGuide", false);
        bannerDescription = intent.getStringExtra("bannerDescription");
        bannerPicture = intent.getStringExtra("bannerPicture");
        bannerTitle = intent.getStringExtra("bannerTitle");
        temp_loadUrl = intent.getStringExtra("bannerUrl");
        content = intent.getStringExtra("content");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTimeOutCallBack(TimeOutEvent event) {
        if (event.isSuccess) {
            if (isFromGuide) {
                startActivity(new Intent().setClass(mActivity, HomeActivity.class));
            }
            finish();
        }
    }

    @Override
    public void onBackPressed() {
        if (isFromGuide) {
            startActivity(new Intent().setClass(mActivity, HomeActivity.class));
        }
        finish();
    }

    public void onshouldOverrideUrlLoadingCallBack(WebView webview, String web_url) {
        loadUrl = web_url;
        if (web_url.contains("fundDetail")) {
            String url = null;
            try {
                url = URLDecoder.decode(web_url, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            Log.e(TAG, "url=" + url);
            String fundcode;
            String fundType;
            String mainTitle;
            String subTitle;
            Map<String, String> map = new HashMap<>();
            String[] params = url.split("\\?")[1].split("&");
            for (int i = 0; i < params.length; i++) {
                //System.out.println("params--" + params[i]);
                String key = params[i].split("=")[0];
                String value = "";
                try {
                    value = params[i].split("=")[1];
                } catch (Exception exception) {
                    MentorLogger.Log(TAG, "value为null");
                }
                map.put(key, value);
            }
            fundcode = map.get("fundCode");
            fundType = map.get("fundType");
            mainTitle = map.get("fundName") + "  " + map.get("fundCode");
            subTitle = map.get("fundstateDescription");

            mIntent.setClass(mActivity, FundDetailActivity.class);
            mIntent.putExtra("fundcode", fundcode);
            mIntent.putExtra("fundType", fundType);
            mIntent.putExtra("fundname", map.get("fundName"));
            mIntent.putExtra("mainTitle", mainTitle);
            mIntent.putExtra("subTitle", subTitle);
            startActivity(mIntent);
        } else {
            if (web_url.contains("sharePermit")) {
                shareButtonTitle1.setVisibility(View.VISIBLE);
            } else {
                shareButtonTitle1.setVisibility(View.INVISIBLE);
            }
            webview.loadUrl(web_url);
        }
    }

    @OnClick({R.id.shareButtonTitle1})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.shareButtonTitle1:
                if (StringUtils.isNullOrEmpty(bannerTitle)) {
                    bannerTitle = "广告";
                }

//                SharePopup.Share(mActivity, bannerTitle, loadUrl, bannerDescription, bannerPicture);
//                Log.e("lty", "onClick:分享数据  bannerTitle="+bannerTitle+" ,loadUrl="+loadUrl
//                        +" ,bannerDescription"+ bannerDescription+" ,bannerPicture="+bannerPicture);
//                SharePopup.Share(mActivity, ""+bannerTitle,shareUrl, "点击查看详情");

                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
